package trocabi.view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import trocabi.DAO.DAODepositaire;
import trocabi.Parameters;
import trocabi.Socle.JNumberTextField;
import trocabi.Socle.JStringTextField;
import trocabi.Socle.TechnicalException;
import trocabi.TROCABI;
import trocabi.model.Depositaire;
import trocabi.service.DepositaireServices;

public class GuiSaisieDepositaire extends JFrame implements DocumentListener {
    private static final Logger           logger = Logger.getLogger("trocabi.view.GuiSaisieDepositaire");
    private Depositaire                   depositaire;
    private DepositaireServices           depositaireServices;
    private GuiDeposerArticles            guiDeposerArticles;
    private JButton                       btAnnuler;
    private JButton                       btValider;
    private JTextField                    fieldId;
    private JStringTextField              fieldNom=new JStringTextField(DAODepositaire.FD_NOM_SIZE,true);
    private JStringTextField              fieldPrenom=new JStringTextField(DAODepositaire.FD_PRENOM_SIZE,false);
    private JNumberTextField              fieldTelFixe = new JNumberTextField(Parameters.FORMAT_TEL);
    private JNumberTextField              fieldTelPortable = new JNumberTextField(Parameters.FORMAT_TEL);
    private JStringTextField              fieldRue=new JStringTextField(DAODepositaire.FD_RUE_SIZE,false);
    private JStringTextField              fieldVille=new JStringTextField(DAODepositaire.FD_VILLE_SIZE,false);
    private JNumberTextField              fieldCP=  new JNumberTextField(Parameters.FORMAT_CP);
    private JStringTextField              fieldIDCard = new JStringTextField(DAODepositaire.FD_IDCARD_SIZE,false);
    private JPanel                        pContentPanel;
    private JPanel                        pCenter;

    public GuiSaisieDepositaire() {
        initComponents();
        depositaireServices=new DepositaireServices();
    }

    public void setGuiDeposerArticles(GuiDeposerArticles guiDeposerArticles) {
        this.guiDeposerArticles=guiDeposerArticles;
    }
    
    private void initComponents() {
        this.setTitle("Dépôt : Informations dépositaire");
        this.setSize(500, 500);
        this.setLocationRelativeTo(null);
        this.setResizable(false);
        this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

        // Content panel de type BorderPanel --> nord = titre / centre = contenu / sud = licence, droits, auteurs ...
        pContentPanel = new JPanel(new BorderLayout());
        pContentPanel.setBackground(Color.white);
        this.setContentPane(pContentPanel);

        /*
         * Que du gridBagLayout
         * 2 colonnes / 11 lignes
         */
        pCenter = new JPanel(new GridBagLayout());
        GridBagConstraints wPos = new GridBagConstraints();
        wPos.gridx = 0;
        wPos.gridy = 0;
        wPos.insets = new Insets(10, 10, 10, 10);
        wPos.anchor = GridBagConstraints.LINE_START;

        pCenter.add(new JLabel("Identifiant :"), wPos);
        wPos.gridy++;
        pCenter.add(new JLabel("Nom :"), wPos);
        wPos.gridy++;
        pCenter.add(new JLabel("Prénom :"), wPos);
        wPos.gridy++;
        pCenter.add(new JLabel("Adresse"), wPos);
        wPos.gridy++;
        wPos.insets = new Insets(10, 40, 10, 10);
        pCenter.add(new JLabel("Rue :"), wPos);
        wPos.gridy++;
        pCenter.add(new JLabel("Ville :"), wPos);
        wPos.gridy++;
        pCenter.add(new JLabel("Code Postal :"), wPos);
        wPos.gridy++;
        wPos.insets = new Insets(10, 10, 10, 10);
        pCenter.add(new JLabel("Tel. Fixe :"), wPos);
        wPos.gridy++;
        pCenter.add(new JLabel("Tel. Portable :"), wPos);
        wPos.gridy++;
        pCenter.add(new JLabel("N° Carte Identité :"), wPos);

        wPos.gridx = 1;
        wPos.gridy = 0;
        wPos.weightx = 1;
        fieldId = new JTextField();
        fieldId.setEditable(false);
        fieldId.setPreferredSize(new Dimension(150, 20));
        pCenter.add(fieldId, wPos);
        wPos.gridy++;     
        fieldNom.getDocument().addDocumentListener(this);
        fieldNom.setPreferredSize(new Dimension(150, 20));  
        pCenter.add(fieldNom, wPos);
        fieldPrenom.getDocument().addDocumentListener(this);
        fieldPrenom.setPreferredSize(new Dimension(150, 20));
        wPos.gridy++; 
        pCenter.add(fieldPrenom, wPos);
        fieldRue.getDocument().addDocumentListener(this);
        fieldRue.setPreferredSize(new Dimension(300, 20));
        wPos.gridy+=2; // skip "addresse" bloc
        pCenter.add(fieldRue, wPos);
        fieldVille.getDocument().addDocumentListener(this);
        fieldVille.setPreferredSize(new Dimension(300, 20));
        wPos.gridy++;
        pCenter.add(fieldVille, wPos);
        
       
       
        fieldCP.getDocument().addDocumentListener(this);
        fieldCP.setPreferredSize(new Dimension(100, 20));
        wPos.gridy++;
        pCenter.add(fieldCP, wPos);
     
        fieldTelFixe.getDocument().addDocumentListener(this);
        fieldTelFixe.setPreferredSize(new Dimension(100, 20));
        wPos.gridy++;
        pCenter.add(fieldTelFixe, wPos);
       
        fieldTelPortable.getDocument().addDocumentListener(this);
        fieldTelPortable.setPreferredSize(new Dimension(100, 20));
        wPos.gridy++;
        pCenter.add(fieldTelPortable, wPos);
     
        fieldIDCard.getDocument().addDocumentListener(this);
        fieldIDCard.setPreferredSize(new Dimension(100, 20));
        wPos.gridy++;
        pCenter.add(fieldIDCard, wPos);
        btValider = new JButton("Valider");
        btValider.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                validerDepositaire();
            }
        });
        wPos.gridy++;
        wPos.insets = new Insets(20, 10, 0, 10);
        wPos.anchor = GridBagConstraints.LINE_END;
        pCenter.add(btValider, wPos);
        btAnnuler = new JButton("Annuler");
        btAnnuler.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
            }
        });
        wPos.gridx = 0;
        wPos.anchor = GridBagConstraints.LINE_START;
        pCenter.add(btAnnuler, wPos);
        pContentPanel.add(pCenter);
    }

    public void clear() {
        depositaire = null;
        this.setLocationRelativeTo(null);
        fieldId.setText("");
        fieldNom.setText("");
        fieldPrenom.setText("");
        fieldRue.setText("");
        fieldVille.setText("");
        fieldCP.setText("0");
        fieldTelFixe.setText("0");
        fieldTelPortable.setText("0");
        fieldIDCard.setText("");
        btValider.setEnabled(false);
    }

    public void setDepositaire(Depositaire dpDepositaire_tmp) {
        depositaire = dpDepositaire_tmp;
        fieldId.setText(String.format(Parameters.FORMAT_ID_DEPOSITAIRE,depositaire.getId()));
        fieldNom.setText(TROCABI.formatageString(depositaire.getNom()));
        fieldPrenom.setText(TROCABI.formatageString(depositaire.getPrenom()));
        fieldRue.setText(TROCABI.formatageString(depositaire.getLibelleRue()));
        fieldVille.setText(TROCABI.formatageString(depositaire.getLibelleVille()));
        fieldCP.setText(depositaire.getCodePostal());
        fieldTelFixe.setText(depositaire.getTelFixe());
        fieldTelPortable.setText(depositaire.getTelPortable());
        fieldIDCard.setText(depositaire.getIdCard());
        btValider.setEnabled(true);
    }

    public void checkTextFields() {
        boolean test=!fieldNom.getText().equals("") &&
                     !fieldPrenom.getText().equals("") &&
                     !fieldRue.getText().equals("") &&
                     !fieldVille.getText().equals("") &&
                     !fieldIDCard.getText().equals(Parameters.FORMAT_IDCARD) &&
                     !fieldCP.getText().equals(Parameters.FORMAT_CP) &&
                     ((!fieldTelFixe.getText().equals(Parameters.FORMAT_TEL) && fieldTelPortable.getText().equals(Parameters.FORMAT_TEL)) ||
                      ( fieldTelFixe.getText().equals(Parameters.FORMAT_TEL) && !fieldTelPortable.getText().equals(Parameters.FORMAT_TEL)) ||
                      (!fieldTelFixe.getText().equals(Parameters.FORMAT_TEL) && !fieldTelPortable.getText().equals(Parameters.FORMAT_TEL)));
        btValider.setEnabled(test);
    }

    @Override
    public void insertUpdate(DocumentEvent de) {
        checkTextFields();
    }

    @Override
    public void removeUpdate(DocumentEvent de) {
        checkTextFields();
    }

    @Override
    public void changedUpdate(DocumentEvent de) {
        checkTextFields();
        
    }
    
    public void validerDepositaire() {
        Depositaire maj;

        // TODO: recherche depositaire deja existant!
        try {
            if (depositaire == null) { // creation d'un depositaire
                maj = new Depositaire(fieldNom.getText(), fieldPrenom.getText(),
                        fieldTelFixe.getText(), fieldTelPortable.getText(),
                        fieldRue.getText(), fieldVille.getText(), fieldCP.getText(),
                        fieldIDCard.getText());
                depositaireServices.create(maj);
            } 
            else { // mise à jour d'un dépositaire
                maj = new Depositaire(depositaire.getId(), fieldNom.getText(), fieldPrenom.getText(),
                        fieldTelFixe.getText(), fieldTelPortable.getText(),
                        fieldRue.getText(), fieldVille.getText(), fieldCP.getText(),
                        fieldIDCard.getText());
                depositaireServices.update(maj);
            }
            depositaire = maj;
            guiDeposerArticles.setDepositaire(depositaire);
            guiDeposerArticles.setVisible(true);
        } catch (TechnicalException e) {
            TROCABI.fenetreExterne(TROCABI.ERREUR, e.getMessage());
        }
        setVisible(false);
    }
}
